package com.cssw.fyzb.tps.api.im;

import com.cssw.fyzb.tps.service.im.MessageService;
import com.cssw.fyzb.tps.service.im.common.ImHttpComm;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;

/**
 * @Author Jian Qin.
 */
@Function(description = "查询单聊消息", parameters = {
        @Parameter(name = "from_Account", type = Type.String, description = "消息发送方 UserID"),
        @Parameter(name = "to_Account", type = Type.String, description = "消息接收方 UserID"),
        @Parameter(name = "maxCnt", type = Type.Integer, description = "请求的消息条数"),
        @Parameter(name = "minTime", type = Type.String, description = "请求的消息时间范围yyyyMMddHHmmss"),
        @Parameter(name = "maxTime", type = Type.String, description = "请求的消息时间范围yyyyMMddHHmmss"),
        @Parameter(name = "lastMsgKey", type = Type.String, description = "上一次拉取到的最后一条消息的 MsgKey，续拉时需要填该字段", required = false),
})
@Component
public class GetRoamMsg implements Action {
    @Autowired
    private MessageService messageService;
    @Override
    public Response execute(Request request) throws Exception {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
        String fromAccount = request.getString("from_Account");
        String toAccount = request.getString("to_Account");
        long maxCnt = request.getLong("maxCnt");
        long minTime = fmt.parse(request.getString("minTime")).getTime() / 1000;
        long maxTime = fmt.parse(request.getString("maxTime")).getTime() / 1000;
        String lastMsgKey = request.getString("lastMsgKey");

        ImHttpComm.ImResult result = messageService.getRoamMsg(fromAccount, toAccount, maxCnt, minTime, maxTime, lastMsgKey);
        if(result.getErrorCode() == 0){
            return Response.success()
                    .put("complete", result.getInteger("Complete"))
                    .put("msgCnt", result.getInteger("MsgCnt"))
                    .put("lastMsgTime", result.getInteger("LastMsgTime"))
                    .put("lastMsgKey", result.getString("LastMsgKey"))
                    .put("MsgList", result.getList("MsgList"));
        }else{
            return Response.fail(result.getErrorInfo(), result.getErrorCode());
        }
    }
}
